<?php
class Custom_Controller_Action_Default_Filemanager extends  Thamza_Controller_MainController {
	public $rootDirUpload;
	public $caherootDirUpload;
	public $rootDir;
	/*public function init() {
		// Setting for multi templates
		$layoutPath = APPLICATION_PATH . '/templates/default';
		$options = array ('layout' => 'index', 'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $options );
		// End setting for multi templates

		$this->rootDirUpload = BASE_PATH.'/public/uploads/data';
		$this->cacherootDirUpload = BASE_PATH.'/public/uploads/cache/data';
		$this->view->assign ( 'name', 'Image Manager' );
		$this->view->assign ( 'ctrlName', 'filemanager' );
		$this->view->assign ( 'hastrash', '' );
		$this->view->assign ( 'tileicon', 'img/category.png' );
		$this->view->assign('title','Image Manager');
		$this->view->copyable = '';

		if ($this->getRequest ()->isXmlHttpRequest ()) {
			$this->_helper->layout->disableLayout ();
			$ajaxContext = $this->_helper->getHelper ( 'AjaxContext' );
			$ajaxContext->addActionContext ( 'view', 'html' );
			$ajaxContext->initContext ();
		}

		$ajaxContext = $this->_helper->getHelper ( 'AjaxContext' );

		$ajaxContext->addActionContext ( 'view', 'html' )->addActionContext ( 'form', 'html' )
		->addActionContext ( 'create', 'json' )
		->addActionContext ( 'directory', 'json' )
		->addActionContext ( 'image', 'json' )
		->addActionContext ( 'save', 'json' )
		->addActionContext ( 'delete', 'json' )
		->addActionContext ( 'copy', 'json' )
		->addActionContext ( 'move', 'json' )
		->addActionContext ( 'files', 'json' )
		->addActionContext ( 'rename', 'json' )
		->addActionContext ( 'upload', 'json' )
		->initContext ();
	}
*/
	public function preDispatch() {
		/*
		$ntd = new Zend_Session_Namespace ( 'employerntd' );//nha tuyen dung
		
		$moduleName  = $this->getRequest()->getModuleName();
		
		if( $moduleName == "employer" ){
			if (! isset($ntd->employerntd)) {
				if ($this->_request->getActionName () != 'index') {
					$this->_redirect ( '/employer' );
				}
			} else{
				$el = explode('@',$ntd->employerntd['email']);
				$this->rootDir = strtolower($el[0]);
				if(!is_dir($this->rootDirUpload.'/'.$this->rootDir)) {
					mkdir($this->rootDirUpload . '/' . str_replace('../', '', $this->rootDir), 0777);
					$this->rootDirUpload .= '/'.$this->rootDir;
				} else {
					$this->rootDirUpload .= '/'.$this->rootDir;
				}
				$this->cacherootDirUpload .= '/'.$this->rootDir;
			}
		}else if($moduleName == "front" ){
			
			$auth = Zend_Auth::getInstance ();//nguoi tim viec
			if (! $auth->hasIdentity ()) {
				if ($this->_request->getActionName () != 'index') {
					$this->_redirect ( '/' );
				}
			} else{
				$infoUser = $auth->getIdentity ();
				$el = explode('@',$infoUser->email);
				
				$this->rootDir = strtolower($el[0]);
				if(!is_dir($this->rootDirUpload.'/'.$this->rootDir)) {
					mkdir($this->rootDirUpload . '/' . str_replace('../', '', $this->rootDir), 0777);
					$this->rootDirUpload .= '/'.$this->rootDir;
				} else {
					$this->rootDirUpload .= '/'.$this->rootDir;
				}
				$this->cacherootDirUpload .= '/'.$this->rootDir;	
			}
		}
		/**/
		$this->rootDir = "admin";
		if(!is_dir($this->rootDirUpload.'/'.$this->rootDir)) {
			mkdir($this->rootDirUpload . '/' . str_replace('../', '', $this->rootDir), 0777);
			$this->rootDirUpload .= '/'.$this->rootDir;
		} else {
			$this->rootDirUpload .= '/'.$this->rootDir;
		}
		$this->cacherootDirUpload .= '/'.$this->rootDir;
		
	}

	public function indexAction() {
		$this->_helper->layout->disableLayout ();
		$this->view->assign('entry_folder','New Folder:');
		$this->view->assign('entry_move','Move:');
		$this->view->assign('entry_copy','Name:');
		$this->view->assign('entry_rename','Name:');

		$this->view->assign('button_folder','New Folder');
		$this->view->assign('button_delete','Delete');
		$this->view->assign('button_move','Move');
		$this->view->assign('button_copy','Copy');
		$this->view->assign('button_rename','Rename');
		$this->view->assign('button_upload','Upload');
		$this->view->assign('button_refresh','Refresh');

		$this->view->assign('error_select','Warning: Please select a directory or file!');
		$this->view->assign('error_directory','Warning: Please select a directory!');

		$this->view->assign('directory',$this->rootDirUpload.'/');
		
		$field = $this->_getParam ( 'field', '' );
		$this->view->field = $field;
		
		$thumb = $this->_getParam ( 'thumb', '' );
		$this->view->thumb = $thumb;
		
		$preview = $this->_getParam ( 'preview', '' );
		$this->view->preview = $preview;

		//		if (isset($this->request->get['CKEditorFuncNum'])) {
		//			$this->view->assign('fckeditor','');// $this->request->get['CKEditorFuncNum'];
		//		} else {
		//			$this->view->assign('fckeditor','');// false;
		//		}

	}

	public function imageAction() {
		$model = new Custom_Model_Filemanager();
		$image = $this->getRequest ()->getPost ('image');
		if (isset($image)) {
			$model->resize($image, 200, 200);
		}
	}

	public function directoryAction() {
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();
		
		$json = array();
		$directoryFrm = $this->getRequest ()->getPost ('directory');
		if (isset($directoryFrm)) {
			$directories = glob(rtrim($this->rootDirUpload.'/' . str_replace('../', '', $directoryFrm), '/') . '/*', GLOB_ONLYDIR);
			if ($directories) {
				$i = 0;
				foreach ($directories as $directory) {
					$json[$i]['data'] = basename($directory);
					$json[$i]['attributes']['directory'] = substr($directory, strlen($this->rootDirUpload.'/'));

					$children = glob(rtrim($directory, '/') . '/*', GLOB_ONLYDIR);

					if ($children)  {
						$json[$i]['children'] = ' ';
					}
					$i++;
				}
			}
		}
		$jsonO = Zend_Json::encode ( $json );
		echo $jsonO;
	}

	public function filesAction() {
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();
        
		$json = array();
		$model = new Custom_Model_Filemanager();

		$direct = $this->getRequest()->getPost('directory');
		if (isset($direct) && $direct) {
			$directory = $this->rootDirUpload.'/' . str_replace('../', '', $direct);
		} else {
			$directory = $this->rootDirUpload.'/';
		}
        
		$allowed = array(
			'.jpg',
			'.jpeg',
			'.png',
			'.gif'
			);

			$files = glob(rtrim($directory, '/') . '/*');
            
			if ($files) {
				$i = 0;
				foreach ($files as $file) {
					
					if (is_file($file)) {
						$ext = strrchr($file, '.');
					} else {
						$ext = '';
					}
                    
					if (in_array(strtolower($ext), $allowed)) {
						$size = filesize($file);

						$i = 0;

						$suffix = array(
						'B',
						'KB',
						'MB',
						'GB',
						'TB',
						'PB',
						'EB',
						'ZB',
						'YB'
						);

						while (($size / 1024) > 1) {
							$size = $size / 1024;
							$i++;
						}
						
//						$thumb = $model->resize(substr($file, strlen(UPLOAD_PATH)), 200, 200);
//						
//						$basename = basename(dirname($_SERVER["SCRIPT_NAME"]));
//						
//						$thumbs = explode($basename,$thumb);
//						$thumb_file = '';
//						$i = 0;
//						foreach($thumbs as $thum) {
//							if($i > 0 && !empty($thum)) {
//								$thumb_file .= str_replace('//','/',$thum);
//							}
//							$i++;
//						}
						
						$json[] = array(
						'file'     => substr($file, strlen($this->rootDirUpload.'/')),
						'filename' => basename($file),
						'size'     => round(substr($size, 0, strpos($size, '.') + 4), 2) . $suffix[$i],
						'thumb'    => $model->resize(substr($file, strlen(UPLOAD_PATH)), 200, 200),
						);
					}
				}
			}
			$jsonO = Zend_Json::encode ( $json );
			echo $jsonO;
	}

	public function createAction() {
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();
		$arr = array();
		$direct = $this->getRequest ()->getPost ('directory');
		$name = $this->getRequest ()->getPost ('name');
		if (isset($direct)) {
			if (isset($name) || $name) {
				$directory = rtrim($this->rootDirUpload.'/' . str_replace('../', '', $direct), '/');

				if (!is_dir($directory)) {
					$arr['error'] = 'Warning: Please select a directory!';
				}

				if (file_exists($directory . '/' . str_replace('../', '', $name))) {
					$arr['error'] = 'Warning: A file or directory with the same name already exists!';
				}
			} else {
				$arr['error'] = 'Warning: Please enter a new name!';
			}
		} else {
			$arr['error'] = 'Warning: Please select a directory!';
		}

		if (!isset($arr['error'])) {
			mkdir($directory . '/' . str_replace('../', '', $name), 0777);
				
			$arr['success'] = 'Success: Directory created!';
		}
		$json = Zend_Json::encode ( $arr );
		echo $json;
	}

	public function deleteAction() {
		$model = new Custom_Model_Filemanager();
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();
		$json = array();
		$path = $this->getRequest()->getPost('path');
		$temp = $this->getRequest()->getPost('cache');
		$cache = isset($temp)?$temp:$this->getRequest()->getPost('path');
		if (isset($path)) {
			$path = rtrim($this->rootDirUpload.'/' . str_replace('../', '', $path), '/');
			$cache = rtrim($this->cacherootDirUpload .'/' . str_replace('../', '', $cache), '/');
				
			if (!file_exists($path)) {
				$json['error'] = 'Warning: Please select a directory or file!';
			}
				
			if ($path == rtrim($this->rootDirUpload.'/', '/')) {
				$json['error'] = 'Warning: You can not delete this directory!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory or file!';
		}

		if (!isset($json['error'])) {
			if (is_file($path)) {
				unlink($path);
			} elseif (is_dir($path)) {
				$this->recursiveDelete($path);
			}
			if (is_file($cache)) {
				unlink($cache);
			} elseif (is_dir($cache)) {
				$this->recursiveDelete($cache);
			}
			$json['success'] = 'Success: Your file or directory has been deleted!';
		}

		$jsonO = Zend_Json::encode ( $json );
		echo $jsonO;
	}

	protected function recursiveDelete($directory) {
		if (is_dir($directory)) {
			$handle = opendir($directory);
		}

		if (!$handle) {
			return false;
		}

		while (false !== ($file = readdir($handle))) {
			if ($file != '.' && $file != '..') {
				if (!is_dir($directory . '/' . $file)) {
					unlink($directory . '/' . $file);
				} else {
					$this->recursiveDelete($directory . '/' . $file);
				}
			}
		}

		closedir($handle);

		rmdir($directory);

		return true;
	}

	public function moveAction() {
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();

		$json = array();
		$fromFrm = $this->getRequest()->getPost('from');
		$toFrm = $this->getRequest()->getPost('to');

		if (isset($fromFrm) && isset($toFrm)) {
			$from = rtrim($this->rootDirUpload.'/' . str_replace('../', '', $fromFrm), '/');
				
			if (!file_exists($from)) {
				$json['error'] = 'Warning: File or directory does not exist!';
			}
				
			if ($from == $this->rootDirUpload) {
				$json['error'] = 'Warning: Can not alter your default directory!';
			}
				
			$to = rtrim($this->rootDirUpload.'/' . str_replace('../', '', $toFrm), '/');

			if (!file_exists($to)) {
				$json['error'] = 'Warning: Move to directory does not exists!';
			}
				
			if (file_exists($to . '/' . basename($from))) {
				$json['error'] = 'Warning: A file or directory with the same name already exists!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory!';
		}

		if (!isset($json['error'])) {
			rename($from, $to . '/' . basename($from));
				
			$json['success'] = 'Success: Your file or directory has been moved!';
		}

		$jsonO = Zend_Json::encode ( $json );
		echo $jsonO;
	}

	public function copyAction() {
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();

		$model = new Custom_Model_Filemanager();

		$json = array();

		$path = $this->getRequest()->getPost('path');
		$name = $this->getRequest()->getPost('name');

		if (isset($path) && isset($name)) {
			if ((strlen(utf8_decode($name)) < 3) || (strlen(utf8_decode($name)) > 255)) {
				$json['error'] = 'Warning: Filename must be a between 3 and 255!';
			}

			$old_name = rtrim($this->rootDirUpload.'/' . str_replace('../', '', $path), '/');
				
			if (!file_exists($old_name) || $old_name == $this->rootDirUpload) {
				$json['error'] = 'Warning: Can not copy this file or directory!';;
			}
				
			if (is_file($old_name)) {
				$ext = strrchr($old_name, '.');
			} else {
				$ext = '';
			}
				
			$new_name = dirname($old_name) . '/' . str_replace('../', '', $name . $ext);

			if (file_exists($new_name)) {
				$json['error'] = 'Warning: A file or directory with the same name already exists!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory or file!';
		}

		if (!isset($json['error'])) {
			if (is_file($old_name)) {
				copy($old_name, $new_name);
			} else {
				$this->recursiveCopy($old_name, $new_name);
			}
				
			$json['success'] = 'Success: Your file or directory has been copied!';
		}

		$jsonObj = Zend_Json::encode ( $json );
		echo $jsonObj;
	}

	function recursiveCopy($source, $destination) {
		$directory = opendir($source);

		@mkdir($destination);

		while (false !== ($file = readdir($directory))) {
			if (($file != '.') && ($file != '..')) {
				if (is_dir($source . '/' . $file)) {
					$this->recursiveCopy($source . '/' . $file, $destination . '/' . $file);
				} else {
					copy($source . '/' . $file, $destination . '/' . $file);
				}
			}
		}

		closedir($directory);
	}

	public function foldersAction() {
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();
		$json = $this->recursiveFolders($this->rootDirUpload.'/');
		echo $json;
	}

	protected function recursiveFolders($directory) {
		$output = '';

		$output .= '<option value="' . substr($directory, strlen($this->rootDirUpload . '/')) . '">' . substr($directory, strlen($this->rootDirUpload . '/')) . '</option>';

		$directories = glob(rtrim(str_replace('../', '', $directory), '/') . '/*', GLOB_ONLYDIR);

		foreach ($directories  as $directory) {
			$output .= $this->recursiveFolders($directory);
		}

		return $output;
	}

	public function renameAction() {

		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();

		$model = new Custom_Model_Filemanager();

		$json = array();
		$path = $this->getRequest()->getPost('path');
		$name = $this->getRequest()->getPost('name');
		if (isset($path) && isset($name)) {
			if ((strlen(utf8_decode($name)) < 3) || (strlen(utf8_decode($name)) > 255)) {
				$json['error'] = 'Warning: Filename must be a between 3 and 255!';
			}

			$old_name = rtrim($this->rootDirUpload.'/' . str_replace('../', '', $path), '/');
				
			if (!file_exists($old_name) || $old_name == $this->rootDirUpload) {
				$json['error'] = 'Warning: Can not rename this directory!';
			}
				
			if (is_file($old_name)) {
				$ext = strrchr($old_name, '.');
			} else {
				$ext = '';
			}
				
			$new_name = dirname($old_name) . '/' . str_replace('../', '', $name . $ext);

			if (file_exists($new_name)) {
				$json['error'] = 'Warning: A file or directory with the same name already exists!';
			}
		}

		if (!isset($json['error'])) {
			rename($old_name, $new_name);
				
			$json['success'] = 'Success: Your file or directory has been renamed!';
		}

		$jsonObj = Zend_Json::encode ( $json );
		echo $jsonObj;
	}

	public function uploadAction() {
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();

		$model = new Custom_Model_Filemanager();

		$json = array();

		$direct = $this->getRequest()->getPost('directory');
		$files = $_FILES['image'];
		if (isset($direct)) {
			if (isset($files) && $files['tmp_name']) {
				if ((strlen(utf8_decode($files['name'])) < 3) || (strlen(utf8_decode($files['name'])) > 255)) {
					$json['error'] = 'Warning: Filename must be a between 3 and 255!';
				}
					
				$directory = rtrim($this->rootDirUpload . '/' . str_replace('../', '', $direct), '/');

				if (!is_dir($directory)) {
					$json['error'] = 'Warning: Please select a directory!';
				}

				if ($files['size'] > 30000000000) {
					$json['error'] = 'Warning: File to big please keep below 300kb and no more than 1000px height or width!';
				}

				$allowed = array(
					'image/jpeg',
					'image/pjpeg',
					'image/png',
					'image/x-png',
					'image/gif',
					'application/x-shockwave-flash'
					);

					if (!in_array($files['type'], $allowed)) {
						$json['error'] = 'Warning: Incorrect file type!';
					}

					$allowed = array(
					'.jpg',
					'.jpeg',
					'.gif',
					'.png',
					'.flv'
					);

					if (!in_array(strtolower(strrchr($files['name'], '.')), $allowed)) {
						$json['error'] = 'Warning: Incorrect file type!';
					}


					if ($files['error'] != UPLOAD_ERR_OK) {
						$json['error'] = 'error_upload_' . $files['error'];
					}
			} else {
				$json['error'] = 'Warning: Please select a file!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory!';
		}

		if (!isset($json['error'])) {
			$filename = $directory . '/' . basename($files['name']);
			if (@move_uploaded_file($files['tmp_name'], $filename)) {
				$json['success'] = 'Success: Your file has been uploaded!';
			} else {
				$json['error'] = 'Warning: File could not be uploaded for an unknown reason!';
			}
		}

		$jsonObj = Zend_Json::encode ( $json );
		echo $jsonObj;
	}
}
?>